package com.zlb.app.common.strategy.impl;

import cn.hutool.core.io.FileUtil;
import com.zlb.app.common.constant.Constants;
import com.zlb.app.common.exception.BusinessException;
import com.zlb.app.common.properties.ProjectProperties;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;

/**
 * @Desc 文件上传系统实现类
 * @Author zWX1367238
 * @Date 2024-08-16 11:17:17
 **/
@Service("projectUploadStrategyImpl")
public class ProjectUploadStrategyImpl extends AbstractUploadStrategyImpl {

    @Value("${server.port}")
    public String port;

    @Value("${server.servlet.context-path:}")
    public String contextPath;

    @Autowired
    private ProjectProperties projectProperties;

    @Override
    public Boolean exists(String filePath) {
        return false;
    }

    @Override
    public void upload(String folder, String fileName, InputStream inputStream) throws IOException {
        String tempDir = ResourceUtils.getURL("classpath:").getPath() + projectProperties.getUrl() + folder;
        // 如果目录不存在,先创建目录
        if (!FileUtil.exist(tempDir)) {
            FileUtil.mkdir(new File(tempDir));
        }
        // 创建文件
        File file = new File(tempDir + fileName);
        // 将上传文件写入
        FileOutputStream outputStream = new FileOutputStream(file);
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    }

    @Override
    public String getFileAccessUrl(String filePath) {
        String hostAddress;
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            throw new BusinessException("IP获取异常!");
        }
        return Constants.HTTP_PERFIX + hostAddress + ":" + port + contextPath + projectProperties.getUrl().replaceAll("static|/static","") + filePath;
    }

}
